﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using DotNetNuke.Entities.Tabs;
using System.Collections;

using System.Collections.Generic;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Framework.Providers;
using DotNetNuke.Services.Localization;
using DotNetNuke.Entities.Portals;

namespace Satrabel.HttpModules.Provider
{
    
    public class TabUrlRuleProvider : UrlRuleProvider
    {

        private const string ProviderType = "urlRule";
        private const string ProviderName = "tabUrlRuleProvider";

        private readonly ProviderConfiguration _providerConfiguration = ProviderConfiguration.GetProviderConfiguration(ProviderType);
        private readonly bool UseKeyWordsDefault = false;

        public TabUrlRuleProvider() {
            var objProvider = (DotNetNuke.Framework.Providers.Provider)_providerConfiguration.Providers[ProviderName];
            if (!String.IsNullOrEmpty(objProvider.Attributes["useKeyWords"]))
            {
                UseKeyWordsDefault = bool.Parse(objProvider.Attributes["useKeyWords"]);
            }
            CacheKeys = new string[] { "Tab_Tabs" };
            Settings = new UrlRuleSetting[] { new UrlRuleSetting("UseKeyWords", UseKeyWordsDefault), new UrlRuleSetting("RemoveHomePage", false) };
            HelpUrl = "https://openurlrewriter.codeplex.com/wikipage?title=TabProvider";
        }

        public override List<UrlRule> GetRules(int PortalId)
        {
            bool useKeyWords = GetPortalSettingAsBoolean(PortalId, "UseKeyWords");
            bool RemoveHomePage = GetPortalSettingAsBoolean(PortalId, "RemoveHomePage");


            List<UrlRule> Rules = new List<UrlRule>();
            TabController tc = new TabController();

            int DefaultHomeTabId;
            if (LocaleController.Instance.GetLocales(PortalId).Count > 1)
            {
                Locale DefaultLocale = LocaleController.Instance.GetDefaultLocale(PortalId);
                PortalInfo objPortal = new PortalController().GetPortal(PortalId, DefaultLocale.Code);
                DefaultHomeTabId = objPortal.HomeTabId;
            }
            else
            {
                DefaultHomeTabId = PortalController.GetCurrentPortalSettings().HomeTabId;
            }


            var tabs = tc.GetTabsByPortal(PortalId);
            foreach (TabInfo tab in tabs.Values)
            {
                if (tab.PortalID > -1 && !tab.TabPath.StartsWith(@"//Admin//") && tab.TabPath != @"//Admin" && !tab.DisableLink && tab.TabType == TabType.Normal)
                {                   
                    var rule = new UrlRule
                    {
                        RuleType = UrlRuleType.Tab,
                        CultureCode = tab.CultureCode,
                        TabId = tab.TabID,
                        Parameters = "tabid="+ tab.TabID.ToString(),
                        Action = UrlRuleAction.Rewrite,
                        Url =  CleanupUrl(GetTabUrl(tab, useKeyWords)),
                        RemoveTab = RemoveHomePage && tab.TabID == DefaultHomeTabId
                    };
                                        
                    TabInfo parentTab = tab;
                    while (parentTab.ParentId != Null.NullInteger )
                    {
                        parentTab = tc.GetTab(parentTab.ParentId);
                        rule.Url = CleanupUrl(GetTabUrl(parentTab, useKeyWords)) + "/" + rule.Url;                        
                    }
                    Rules.Add(rule);                                                                                
                    var ruleRedirect = new UrlRule
                    {
                        RuleType = UrlRuleType.Tab,
                        CultureCode = tab.CultureCode,
                        TabId = tab.TabID,
                        Parameters = "tabid=" + tab.TabID.ToString(),
                        Action = UrlRuleAction.Redirect,
                        Url = tab.TabPath.Replace("//", "/").TrimStart('/').ToLower(),
                        RedirectDestination = rule.Url,
                        RemoveTab = RemoveHomePage && tab.TabID == DefaultHomeTabId
                    };
                    if (rule.Url != ruleRedirect.Url)
                    {
                        Rules.Add(ruleRedirect);  
                    }
                }
            }
            return Rules;
        }

        protected string GetTabUrl(TabInfo tab, bool useKeyWords)
        {            
            if (useKeyWords && tab.KeyWords != "")
            {
                string[] keys = tab.KeyWords.Trim().Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries);
                if (keys.Length > 0 && keys[0].Trim() != ""){
                    return keys[0].Trim();
                }            
            }
            return tab.TabName;
        }
        
    }
}